package com.itserver.utils.filter;

import com.itserver.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter("/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("TokenFilter执行了");
        // 1 login 接口不需要拦截
//        if (request.getRequestURI().contains("/login")) {
//            filterChain.doFilter(servletRequest, servletResponse);
//            return;
//        }

//        //2 获取请求头中的token
//        String token = request.getHeader("Authorization");
//
//        if (token == null || token.isEmpty()) {
//            log.info("token为空,返回401");
//            // 返回401
//            response.setContentType("application/json;charset=UTF-8");
//            response.getWriter().write("{\"code\":\"401\",\"msg\":\"token为空\"}");
//            return;
//        }
//        //3 解析token
//        Claims claims = JwtUtils.parseJWT(token);
//        if (claims == null) {
//            log.info("token无效,响应401");
//            response.setContentType("application/json;charset=UTF-8");
//            response.getWriter().write("{\"code\":\"401\",\"msg\":\"token无效\"}");
//            return;
//        }
//
//        //4 Token 验证通过
//        log.info("token有效,放行");

        filterChain.doFilter(servletRequest, servletResponse);
    }
}

